package com.laker.autotest.desktop.core;

import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import org.opencv.core.Mat;
import org.opencv.core.Point;

/**
 * 桌面自动化操作工具类，全部基于 java.awt.Robot，适用于任意桌面应用和游戏。
 */
public class DesktopRobotUtil {
    private static Robot robot;

    static {
        try {
            robot = new Robot();
            robot.setAutoDelay(50); // 操作延时，防止过快
        } catch (AWTException e) {
            throw new RuntimeException("初始化 Robot 失败", e);
        }
    }

    /**
     * 鼠标移动到指定坐标
     *
     * @param x 屏幕横坐标
     * @param y 屏幕纵坐标
     */
    public static void moveMouse(int x, int y) {
        robot.mouseMove(x, y);
    }

    /**
     * 鼠标左键点击
     */
    public static void mouseClick() {
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
    }

    /**
     * 鼠标双击
     */
    public static void mouseDoubleClick() {
        mouseClick();
        robot.delay(100);
        mouseClick();
    }

    /**
     * 键盘输入字符串（仅支持英文字母和数字）
     *
     * @param text 输入内容
     */
    public static void typeText(String text) {
        boolean canTypeDirectly = true;
        for (char c : text.toCharArray()) {
            int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
            if (keyCode <= 0 || keyCode > KeyEvent.VK_Z) {
                canTypeDirectly = false;
                break;
            }
        }
        if (canTypeDirectly) {
            // 仅英文和数字，逐字符输入
            for (char c : text.toCharArray()) {
                int keyCode = KeyEvent.getExtendedKeyCodeForChar(c);
                robot.keyPress(keyCode);
                robot.keyRelease(keyCode);
            }
        } else {
            // 包含中文或特殊字符，使用剪贴板一次性粘贴
            try {
                // 不再移动鼠标或点击，假定焦点已在目标输入区
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new java.awt.datatransfer.StringSelection(text), null);
                String os = System.getProperty("os.name").toLowerCase();
                if (os.contains("mac")) {
                    robot.keyPress(KeyEvent.VK_META);
                    robot.keyPress(KeyEvent.VK_V);
                    robot.keyRelease(KeyEvent.VK_V);
                    robot.keyRelease(KeyEvent.VK_META);
                } else {
                    robot.keyPress(KeyEvent.VK_CONTROL);
                    robot.keyPress(KeyEvent.VK_V);
                    robot.keyRelease(KeyEvent.VK_V);
                    robot.keyRelease(KeyEvent.VK_CONTROL);
                }
                robot.delay(100);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 按下指定键
     *
     * @param keyCode KeyEvent.VK_*
     */
    public static void keyPress(int keyCode) {
        robot.keyPress(keyCode);
    }

    /**
     * 释放指定键
     *
     * @param keyCode KeyEvent.VK_*
     */
    public static void keyRelease(int keyCode) {
        robot.keyRelease(keyCode);
    }

    /**
     * 屏幕截图并保存到文件
     *
     * @param filePath 保存路径
     */
    public static void captureScreen(String filePath) {
        try {
            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage bufferedImage = robot.createScreenCapture(screenRect);
            ImageIO.write(bufferedImage, "png", new File(filePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查找屏幕上的图片并点击其中心
     * @param templatePath 模板图片路径
     * @return 是否点击成功
     */
    public static boolean findAndClick(String templatePath) {
        Point match = DesktopImageUtil.findImageOnScreen(templatePath);
        if (match != null) {
            // 计算点击位置为模板中心
            Mat template = org.opencv.imgcodecs.Imgcodecs.imread(templatePath);
            int clickX = (int) match.x + template.cols() / 2;
            int clickY = (int) match.y + template.rows() / 2;
            robot.mouseMove(clickX, clickY);
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(100);
            return true;
        }
        return false;
    }

    /**
     * 查找屏幕上的图片并点击其中心，并可选输入文本
     * @param templatePath 模板图片路径
     * @param text 可选输入文本（为 null 或空则只点击）
     * @return 是否操作成功
     */
    public static boolean findAndClickAndType(String templatePath, String text) {
        Point match = DesktopImageUtil.findImageOnScreen(templatePath);
        if (match != null) {
            Mat template = org.opencv.imgcodecs.Imgcodecs.imread(templatePath);
            int clickX = (int) match.x + template.cols() / 2;
            int clickY = (int) match.y + template.rows() / 2;
            robot.mouseMove(clickX, clickY);
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(100);
            if (text != null && !text.isEmpty()) {
                typeText(text);
            }
            return true;
        }
        return false;
    }
}